from fastapi import APIRouter, Depends
from schemas.common import RETURN, ListRequest, Filter
from typing import List, Optional
from fastapi_cache.decorator import cache

import models.admin.system.Dept as DeptModel
import models.admin.system.Admin as AdminModel
from models.Base import StatusTypeEnum

from server.Base import BaseServer
from server.admin.SystemServer import SystemServer
from routers.admin.common import convert_filter_values

from core.Depend import check_token, has_permission


router = APIRouter(prefix="/dept", tags=["部门管理"])


# 添加部门
@router.post("/add",summary="部门添加")
async def add(dept: DeptModel.create_dept, user: AdminModel.redis_admin = Depends(has_permission("system_admin_dep_add"))):
    await BaseServer(DeptModel.Department).create(dept.dict())
    return RETURN.success("添加成功")

# 删除部门
@router.delete("/delete",summary="部门删除")
async def delete(id: int, user: AdminModel.redis_admin = Depends(has_permission("system_admin_dep_del"))):
    await BaseServer(DeptModel.Department).delete(id)
    return RETURN.success("删除成功")

# 修改部门
@router.put("/update",summary="部门修改")
async def update(dept: DeptModel.edit_dept, user: AdminModel.redis_admin = Depends(has_permission("system_admin_dep_edit"))):
    await BaseServer(DeptModel.Department).update(dept.dict())
    return RETURN.success("修改成功")

# 查询部门 
@router.post("/list",summary="部门列表")
async def list(request:ListRequest, user: AdminModel.redis_admin = Depends(has_permission("system_admin_dep_list"))):
    data = await BaseServer(DeptModel.Department).list(request)
    return RETURN.success("查询成功",data)

# 获取所有部门信息
@router.post("/all",summary="部门列表")
@cache(expire=10)
async def all(filters: Optional[List[Filter]] = [], user: AdminModel.redis_admin = Depends(has_permission("system_admin_dep_all"))):
    fields = ["id", "name", "parentId", "phone", "principal", "email", "status", "createtime", "weight", "remark", "type"]
 
    conversion_map = {
        "status": StatusTypeEnum,
    }

    filters = await convert_filter_values(conversion_map,filters)
    data = await SystemServer(DeptModel.Department).getDeptAll(filters,fields=fields)
    return RETURN.success("查询成功",data)


# 查询部门信息
@router.get("/info",summary="部门信息")
async def info(id: int, user: AdminModel.redis_admin = Depends(has_permission("system_admin_dep_info"))):
    data = await BaseServer(DeptModel.Department).get(id)
    return RETURN.success("查询成功",data)